package com.yanqu.road.server.manger.activity.treasure;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.treasure.TreasureActivityPlace;
import com.yanqu.road.entity.activity.treasure.TreasurePlaceProgressInfo;
import com.yanqu.road.entity.activity.treasure.UserTreasureActivityData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.treasure.TreasureActivityModule;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TreasureActivityMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(TreasureActivityMgr.class.getName());

    public static final int CONDITION_TYPE_PROGRESS = eGamePlayerEventType.TreasureActivityProgress.getValue();

    //activityId
    private static Map<Integer, List<TreasureActivityPlace>> placeMapConfig = new ConcurrentHashMap<>();
    //activityId
    private static Map<Integer, Integer> placeRoundConfigMap = new ConcurrentHashMap<>();

    private static RandomHelper random = new RandomHelper();


    @Override
    public boolean reloadData() throws Exception {
        placeMapConfig = new ConcurrentHashMap<>();
        placeRoundConfigMap = new ConcurrentHashMap<>();
        return true;
    }

    public static void reloadActivityInfo() {
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.TreasureActivity.getValue());
        if (activityInfoList != null && activityInfoList.size() > 0) {
            List<Integer> activityIdList = new ArrayList<>();
            for (ActivityInfo activityInfo : activityInfoList) {
                activityIdList.add(activityInfo.getActivityId());
            }
            Map<Integer, List<TreasureActivityPlace>> mapTemp = ActivityBussiness.getActivityPlaceMapInfoMap(activityIdList);
            placeRoundConfigMap = initPlaceRoundMap(mapTemp);
            placeMapConfig = mapTemp;

            playerReloadActivity();
        }
        logger.info("reload Treasure activity end");
    }

 /*   public static void tt(List<ActivityInfo> activityInfoList) {
        for (ActivityInfo ac : activityInfoList) {
            System.out.println(ac.getActivityId() + "***************************************************");
            int currentIndex = 1;
            while (currentIndex < 500) {
                TreasurePlaceProgressInfo placeInfo = getPlaceInfo(ac.getActivityId(), currentIndex);
                System.out.println("round:" + placeInfo.getRound() + " | index:" + currentIndex + " | placeId:" + placeInfo.getPlaceId() + " | routeIndex:" + placeInfo.getRoutProgress());
                currentIndex++;
            }
        }
    }*/

    private static Map<Integer, Integer> initPlaceRoundMap(Map<Integer, List<TreasureActivityPlace>> map) {
        Map<Integer, Integer> resultMap = new ConcurrentHashMap<>();
        for (Map.Entry<Integer, List<TreasureActivityPlace>> e : map.entrySet()) {
            int activityId = e.getKey();
            List<TreasureActivityPlace> placeList = e.getValue();
            int result = 0;
            for (TreasureActivityPlace place : placeList) {
                result += place.getRouteSize() + 1; //大地点也算一个
            }
            resultMap.put(activityId, result);
        }

        return resultMap;
    }

    private static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        for (GamePlayer onlinePlay : playerList) {
            onlinePlay.getModule(TreasureActivityModule.class).syncActivity();
        }
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        return true;
    }


    /**
     * 获取玩家位置信息
     *
     * @param activityId
     * @param currentIndex
     * @return
     */
    public static TreasurePlaceProgressInfo getPlaceInfo(int activityId, int currentIndex) {
        TreasurePlaceProgressInfo placeInfo = new TreasurePlaceProgressInfo();
        try {
            if (!placeMapConfig.containsKey(activityId) || !placeRoundConfigMap.containsKey(activityId)) {
                return placeInfo;
            }

            List<TreasureActivityPlace> placeConfig = placeMapConfig.get(activityId);
            //每轮总共的下标数
            int totalIndex = placeRoundConfigMap.get(activityId);
            //计算轮数
            placeInfo.setRound((currentIndex - 1) / totalIndex);
            //当前轮数的下标
            while (currentIndex > totalIndex) {
                currentIndex = currentIndex - totalIndex;
            }
            //计算大地点 小地点
            int index = 0;
            for (int i = 0; i < placeConfig.size(); i++) {
                TreasureActivityPlace placeTemp = placeConfig.get(i);
                //大地点+当前包含小地点
                index = index + placeTemp.getRouteSize() + 1;
                if (currentIndex <= index) {
                    placeInfo.setPlaceId(placeTemp.getId());
                    placeInfo.setRoutProgress(placeTemp.getRouteSize() - (index - currentIndex));
                    placeInfo.setRewardBox(placeTemp.getRewardBox());
                    placeInfo.setRewardToken(placeTemp.getTokenRewards());
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("getPlaceInfo", e);
        }
        return placeInfo;
    }


    /**
     * 获取随机的步数
     *
     * @param activityInfo
     * @return
     */
    public static int getRandomStepNum(ActivityInfo activityInfo) {
        List<Integer> weightList = getActivityStepRandomWeight(activityInfo);
        int sumWeight = 0;
        for (int weight : weightList) {
            sumWeight += weight;
        }
        int randomValue = random.next(0, sumWeight);

        int tempWeight = 0;
        for (int i = 0; i < weightList.size(); i++) {
            tempWeight += weightList.get(i);
            if (tempWeight > randomValue) {
                return i + 1;
            }
        }
        return 0;
    }

    /**
     * 获取可用送财次数
     *
     * @param userdata
     * @return
     */
    public static int getUserDisperseGoldTimes(UserTreasureActivityData userdata, ActivityInfo activityInfo) {
        if (userdata == null) {
            return 0;
        }
        int useTimes = userdata.getUseTimes();
        if (activityInfo != null) {
            List<String> activityGoldParam = getActivityGoldParam(activityInfo);
            String petTimeNeedScore = activityGoldParam.get(1);
            //总次数-使用的次数
            int allTimes = calcAllTimes(userdata.getTaskProgress(), petTimeNeedScore);
            int result = allTimes - useTimes;
            if (result > 0) {
                return result;
            }
        }
        return 0;
    }

    private static int calcAllTimes(int taskProgress, String petTimeNeedScore) {
        int times = 0;
        String[] scoreNeedArr = petTimeNeedScore.split(";");
        while (taskProgress >= getNeedScore(times, scoreNeedArr)) {
            taskProgress = taskProgress - getNeedScore(times, scoreNeedArr);
            times ++;
        }
        return times;
    }

    private static int getNeedScore(int times, String[] scoreNeedArr) {
        if (times >= scoreNeedArr.length) {
            times = scoreNeedArr.length - 1;
        }
        return Integer.parseInt(scoreNeedArr[times]);
    }

    public static int getUserDisperseGoldTimes(UserTreasureActivityData userdata) {
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(userdata.getActivityId());
        return getUserDisperseGoldTimes(userdata, activityInfo);
    }


    // param3 送財配置-步数随机配置-步数分数配置-每圈信物奖励配置  10000|10|180|300|4|8-10;10;10;10;10;10;10;10-100-1

    /**
     * 送财配置
     * 需达到的积分数|达到的成就值(送菜次数)|银两系数1|银两系数2|随机道具系数1|随机道具系数2
     *
     * @param activityInfo
     * @return
     */
    public static List<String> getActivityGoldParam(ActivityInfo activityInfo) {
        return Arrays.asList(activityInfo.getParam3().split("-")[0].split("\\|"));
    }

    /**
     * 步数随机权重配置
     *
     * @param activityInfo
     * @return
     */
    public static List<Integer> getActivityStepRandomWeight(ActivityInfo activityInfo) {
        return StringUtils.stringToIntegerList(activityInfo.getParam3().split("-")[1], ";");
    }

    /**
     * 步数分数配置
     *
     * @param activityInfo
     * @return
     */
    public static int getActivityStepScore(ActivityInfo activityInfo) {
        return StringUtils.string2intSafe(activityInfo.getParam3().split("-")[2], 0);
    }

    /**
     * 每圈信物奖励
     *
     * @param activityInfo
     * @return
     */
    public static int getActivityRoundTokenReward(ActivityInfo activityInfo) {
        return StringUtils.string2intSafe(activityInfo.getParam3().split("-")[3], 0);
    }


    //param4 消耗道具id|积分id|送財奖励道具id|灵狐信物id

    /**
     * 灵狐信物id
     *
     * @param activityInfo
     * @return
     */
    public static int getActivityTokenId(ActivityInfo activityInfo) {
        return StringUtils.stringToIntegerList(activityInfo.getParam4(), "\\|").get(3);
    }


    /**
     * 送財奖励道具id
     *
     * @param activityInfo
     * @return
     */
    public static int getActivityGoldRewardId(ActivityInfo activityInfo) {
        return StringUtils.stringToIntegerList(activityInfo.getParam4(), "\\|").get(2);
    }

    /**
     * 积分id
     *
     * @param activityInfo
     * @return
     */
    public static int getActivityScoreId(ActivityInfo activityInfo) {
        return StringUtils.stringToIntegerList(activityInfo.getParam4(), "\\|").get(1);
    }

    /**
     * 消耗道具id
     *
     * @param activityInfo
     * @return
     */
    public static int getActivityConsumeId(ActivityInfo activityInfo) {
        return StringUtils.stringToIntegerList(activityInfo.getParam4(), "\\|").get(0);
    }

    /**
     * 领取送財奖励
     *
     * @param earnSpeed 领取奖励的玩家赚速
     * @return
     */
    public static Property getDisperseGoldReward(ActivityInfo activityInfo, BigInteger earnSpeed) {
        List<String> goldParam = getActivityGoldParam(activityInfo);

        //银两奖励
        int totalSilver = random.next(Integer.parseInt(goldParam.get(2)), Integer.parseInt(goldParam.get(3)));
        totalSilver = totalSilver > GameConfig.DISPERSE_GOLD_MAX_SILVER ? GameConfig.DISPERSE_GOLD_MAX_SILVER : totalSilver;
        BigInteger silver = earnSpeed.multiply(BigInteger.valueOf(totalSilver));

        //随机道具奖励
        int goldRewardNum = random.next(Integer.parseInt(goldParam.get(4)), Integer.parseInt(goldParam.get(5)));
        int goldRewardId = getActivityGoldRewardId(activityInfo);

        Property property = new Property();
        property.addProperty(GameConfig.GAME_MONEY_SILVER, silver);
        property.addProperty(goldRewardId, BigInteger.valueOf(goldRewardNum));
        return property;
    }

    public static Map<Integer, List<TreasureActivityPlace>> getPlaceMapConfig() {
        return placeMapConfig;
    }
}
